package com.example.common;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FileUtil {
    public static void appendLineToFile(String filePath, String line) {
        try {
            // 检查文件是否存在，如果不存在则创建文件
            createFileIfNotExists(filePath);

            // 使用BufferedWriter追加行
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath, true))) {
                writer.write(line);
                writer.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void createFileIfNotExists(String filePath) throws IOException {
        Path path = Paths.get(filePath);

        // 如果文件不存在，则创建文件
        if (!Files.exists(path)) {
            Files.createFile(path);
        }
    }

    public static void main(String[] args) {
        String filePath = "path/to/your/file.txt";
        String lineToAdd = "This is a new line.";

        appendLineToFile(filePath, lineToAdd);
        System.out.println("Line appended successfully.");
    }
}
